<?php
namespace app\admin\controller\general;

use app\common\controller\Backend;
use app\common\library\Email;
//use app\common\model\Config as ConfigModel;
use think\Exception;

/**
 * 系统配置
 *
 * @icon fa fa-cogs
 * @remark 可以在此增改系统的变量和分组,也可以自定义分组和变量,如果需要删除请从数据库中删除
 */
class Config extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['check'];

    public function initialize()
    {
        parent::initialize();
        $this->model = model('Config');
    }

    /**
     * 查看
     */
    public function index()
    {
        $siteList = [];
        /*
        $groupList = $this->model->getGroupList();
        foreach ($groupList as $k => $v) {
            $siteList[$k]['name'] = $k;
            $siteList[$k]['title'] = $v;
            $siteList[$k]['list'] = [];
        }
        $con = array();
        $con['1'] = 1;
        $lm = $this->model->select();
        foreach ($this->model->all() as $k => $v) {
            if (!isset($siteList[$v['group']])) {
                continue;
            }
            $value = $v->toArray();
            $value['title'] = __($value['title']);
            if (in_array($value['type'], ['select', 'selects', 'checkbox', 'radio'])) {
                $value['value'] = explode(',', $value['value']);
            }
            $value['content'] = json_decode($value['content'], TRUE);
            $siteList[$v['group']]['list'][] = $value;
        }
        $index = 0;
        foreach ($siteList as $k => &$v) {
            $v['active'] = !$index ? true : false;
            $index++;
        }
        */
        $siteList = config('site.');
        //print_r($siteList);exit;
        $siteself = $siteList['self'];
        unset($siteList['self']);
        $this->view->assign('siteList', $siteList);
        $this->view->assign('siteself', $siteself);

        $selfList = [];
        $list = config('site.');
        foreach ($list as $k => $v) {
            if($k == 'self'){
                foreach ($v as $kk => $vv) {
                    $arr = array();
                    $arr['name'] = $kk;
                    $arr['title'] = $vv;
                    $s = config('self.');
                    $arr['value'] = isset($s[$kk])?$s[$kk]:array();
                    $selfList[] = $arr;
                }
            }
        }
        $this->view->assign('configname', 'self');
        $this->view->assign('selfList', $selfList);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                foreach ($params as $k => &$v) {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try {
                    /*
                    if (in_array($params['type'], ['select', 'selects', 'checkbox', 'radio', 'array'])) {
                        $params['content'] = json_encode(ConfigModel::decode($params['content']), JSON_UNESCAPED_UNICODE);
                    } else {
                        $params['content'] = '';
                    }
                    */
                    $cc = config('site.');
                    /*
                    Array ( [name] => AndiffCMS [beian] => 京ICP备15019846号-2 [cdnurl] => [version] => 1.0.1 [timezone] => Asia/Shanghai [forbiddenip] =>
                    [languages] => Array (
                        [backend] => zh-cn [frontend] => zh-cn ) [fixedpage] => dashboard
                        [categorytype] => Array ( [default] => Default [page] => Page [article] => Article )
                        [configgroup] => Array ( [basic] => Basic [email] => Email [dictionary] => Dictionary [user] => User [example] => Example )
                        [mail_type] => 1 [mail_smtp_host] => smtp.163.com [mail_smtp_port] => 25 [mail_smtp_user] => andiff@163.com [mail_smtp_pass] => password
                        [mail_verify_type] => 0 [mail_from] => andiff@163.com
                        [accessgroup] => all
                        [education] => {"1":"中专及以下","2":"高中","3":"大专","4":"本科","5":"硕士"}
                        [salary] => {"1":"3k以下","2":"3-5k","3":"5-10k","4":"10-20k","5":"50k以上"}
                        [workyear] => {"1":"应届生","2":"1年内","3":"1-3年","4":"3-5年","5":"5-10年","6":"10年以上"}
                        [stime] => {"1":"随时到岗","2":"三天内","3":"一周内","4":"一月内"}
                        [qima] => ) Array (
                            [type] => string [group] => self [name] => dfsdf [title] => 互联网趋势报告 [value] => [content] => value1|title1value2|title2 [tip] => [rule] => [extend] => )


                    Array (
                        [type] => string [group] => self [name] => 3ed [title] => 互联网趋势报告 [value] => [content] => value1|title1value2|title2 [tip] => [rule] => [extend] =>
                        )
                    */
                    $cc['self'][$params['name']] = $params['title'];
                    file_put_contents(ROOT_PATH . 'config' . DS . 'site.php', '<?php' . "\n\nreturn " . var_export($cc, true) . ";");
                    // print_r($cc);
                    // print_r($params);exit;
                    // $result = $this->model->create($params);
                    if ($result !== false) {
                        try {
                            $this->refreshFile();
                            $this->success();
                        } catch (Exception $e) {
                            $this->error($e->getMessage());
                        }
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @param int $ids
     */
    public function edit($ids = NULL)
    {
        if ($this->request->isPost()) {
            $row = $this->request->post("row/a");
            if ($row) {
                $configList = [];
                $cc = config('site.');
                $self = $row['self'];
                unset($row['self']);
                $ary = array();
                foreach ($self as $k => $v) {
                    $r = array();
                    $ary[$v['key']] = $v['value'];

                }
                //print_r($self);exit;
                $row['self'] = $ary;
                /*
                Array ( [name] => AndiffCMS [beian] => 京ICP备15019846号-2 [cdnurl] => [version] => 1.0.1
                [timezone] => Asia/Shanghai [forbiddenip] => [languages] => {"backend":"zh-cn","frontend":"zh-cn"}
                [fixedpage] => dashboard [accessgroup] => all )

                foreach ($this->model->all() as $v) {
                    if (isset($row[$v['name']])) {
                        $value = $row[$v['name']];
                        if (is_array($value) && isset($value['field'])) {
                            $value = json_encode($this->model->getArrayData($value), JSON_UNESCAPED_UNICODE);
                        } else {
                            $value = is_array($value) ? implode(',', $value) : $value;
                        }
                        $v['value'] = $value;
                        $configList[] = $v->toArray();
                    }
                }
                $this->model->allowField(true)->saveAll($configList);
                */
                file_put_contents(ROOT_PATH . 'config' . DS . 'site.php', '<?php' . "\n\nreturn " . var_export($row, true) . ";");
                try {
                    //$this->refreshFile();
                    $this->success();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }

    /**
     * 刷新配置文件
     */
    protected function refreshFile()
    {
        $config = [];
        foreach ($this->model->all() as $k => $v) {

            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], TRUE);
            }
            $config[$value['name']] = $value['value'];
        }
        file_put_contents(APP_PATH . 'extra' . DS . 'site.php', '<?php' . "\n\nreturn " . var_export($config, true) . ";");
    }

    /**
     * 检测配置项是否存在
     * @internal
     */
    public function check()
    {
        $params = $this->request->post("row/a");
        if ($params) {

            $config = $this->model->get($params);
            if (!$config) {
                return $this->success();
            } else {
                return $this->error(__('Name already exist'));
            }
        } else {
            return $this->error(__('Invalid parameters'));
        }
    }

    /**
     * 发送测试邮件
     * @internal
     */
    public function emailtest()
    {
        $row = $this->request->post('row/a');
        \think\Config::set('site', array_merge(\think\Config::get('site'), $row));
        $receiver = $this->request->request("receiver");
        $email = new Email;
        $result = $email
            ->to($receiver)
            ->subject(__("This is a test mail"))
            ->message('<div style="min-height:550px; padding: 100px 55px 200px;">' . __('This is a test mail content') . '</div>')
            ->send();
        if ($result) {
            $this->success();
        } else {
            $this->error($email->getError());
        }
    }

    public function listconfig($configname = 'email'){
        $siteList = [];
        //$list = $this->model->all();
        //print_r(json_encode($list));exit;
        $list = config($configname.'.');

        $this->view->assign('configname', $configname);
        $this->view->assign('sitelist', $list);

        return $this->view->fetch();
    }
    /**
     * 自定义设置
     * @internal
     */
    public function listkeyconfig($configname = 'self'){
        $siteList = [];
        $list = config('site.');
        foreach ($list as $k => $v) {
            if($k == 'self'){
                foreach ($v as $kk => $vv) {
                    $arr = array();
                    $arr['name'] = $kk;
                    $arr['title'] = $vv;
                    $s = config('self.');
                    $arr['value'] = isset($s[$kk])?$s[$kk]:array();
                    $siteList[] = $arr;
                }
            }
        }
        $this->view->assign('configname', $configname);
        $this->view->assign('sitelist', $siteList);
        return $this->view->fetch();
    }

    /**
    * 修改自定义设置
    * @method  post
    * @param array $row
    * @return  成功或失败
    */
    public function updateself(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            $str = '';
            $arr = array();$arrj = array();
            foreach ($params as $k => $v) {
                if(is_array($v)){
                    $arr = array_values($v);
                    foreach ($arr as $kk => $vv) {
                        $arrj[$k][$vv['key']] = $vv['value'];
                    }
                    //$this->model->where(['group'=>$params['configname'],'name'=>$k])->update(['value' => json_encode($arrj,JSON_UNESCAPED_UNICODE)]);
                }else{
                    $str = $v;
                }
            }
            //echo ROOT_PATH . 'config'. DS . 'self.php';exit;
            file_put_contents(ROOT_PATH . 'config' . DS . 'self.php', '<?php' . "\n\nreturn " . var_export($arrj, true) . ";");
            $this->success();exit;
        }
    }
    /**
    * 修改系统设置
    * @method  post
    * @param array $row
    * @return  成功或失败
    */
    public function update(){
        if ($this->request->isPost()){
            $params = $this->request->post("row/a");
            //print_r($params);exit;
            $arrj = array();
            foreach ($params as $k => $v) {


                $arrj[$k] = $v;

                //print_r(ROOT_PATH . 'config' . DS . 'self.php');exit;
                //$this->model->where(['group'=>$params['configname'],'name'=>$k])->update(['value' => json_encode($arrj,JSON_UNESCAPED_UNICODE)]);
            }
            file_put_contents(ROOT_PATH . 'config' . DS . $params['configname'].'.php', '<?php' . "\n\nreturn " . var_export($arrj, true) . ";");
            $this->success();exit;
        }
    }
    public function selfFile(){
        $config = [];
        $list = $this->model->where('group','self')->select();
        foreach ($list as $k => $v) {
            $config[$v['name']] = $v['value'];
        }
        file_put_contents(APP_PATH . 'extra' . DS . 'self.php', '<?php' . "\n\nreturn " . var_export($config, true) . ";");
    }
}
